<template>
  <div class="score-entry">
    <!-- 顶部操作栏 -->
    <div class="header-actions">
      <div class="left-actions">
        <el-button 
          type="primary" 
          @click="handleAdd"
        >
          <el-icon><Plus /></el-icon>
          录入成绩
        </el-button>
        <el-button 
          type="success" 
          @click="handleBatchEntry"
        >
          <el-icon><Upload /></el-icon>
          批量录入
        </el-button>
        <el-button 
          type="warning" 
          @click="handleCalculateRankings"
          :disabled="!selectedEvent"
        >
          <el-icon><Refresh /></el-icon>
          重新计算排名
        </el-button>
      </div>
      <div class="right-actions">
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出成绩
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="请输入运动员姓名、学号或项目名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="比赛项目">
          <el-select 
            v-model="searchForm.eventId" 
            placeholder="请选择项目" 
            clearable 
            filterable 
            style="width: 200px;"
            @change="handleEventChange"
          >
            <el-option 
              v-for="event in events" 
              :key="event.id" 
              :label="event.eventName" 
              :value="event.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成绩类别">
          <el-select v-model="searchForm.isFinal" placeholder="请选择类别" clearable style="width: 120px;">
            <el-option label="全部" :value="null"/>
            <el-option label="预赛" :value="0"/>
            <el-option label="决赛" :value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 成绩统计 -->
    <el-row :gutter="20" class="stats-row" v-if="selectedEvent">
      <el-col :span="6">
        <el-card shadow="never">
          <div class="stat-item">
            <div class="stat-value total">{{ scoreStats.total }}</div>
            <div class="stat-label">总成绩数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never">
          <div class="stat-item">
            <div class="stat-value preliminary">{{ scoreStats.preliminary }}</div>
            <div class="stat-label">预赛成绩</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never">
          <div class="stat-item">
            <div class="stat-value final">{{ scoreStats.final }}</div>
            <div class="stat-label">决赛成绩</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never">
          <div class="stat-item">
            <div class="stat-value participants">{{ scoreStats.participants }}</div>
            <div class="stat-label">参赛人数</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 成绩列表 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="scoreList" 
        :loading="loading" 
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="athleteName" label="运动员姓名" min-width="100" show-overflow-tooltip />
        <el-table-column prop="studentNumber" label="学号" min-width="110" show-overflow-tooltip />
        <el-table-column prop="eventName" label="项目名称" min-width="140" show-overflow-tooltip />
        <el-table-column prop="scoreValue" label="原始成绩" min-width="100" show-overflow-tooltip />
        <el-table-column prop="formattedScoreValue" label="格式化成绩" min-width="120" show-overflow-tooltip />
        <el-table-column prop="scoreType" label="成绩类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getScoreTypeTagType(row.scoreType)">
              {{ getScoreTypeText(row.scoreType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isFinal" label="成绩类别" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isFinal === 1 ? 'success' : 'info'">
              {{ row.isFinal === 1 ? '决赛' : '预赛' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ranking" label="排名" width="80">
          <template #default="{ row }">
            <span v-if="row.ranking">
              {{ getRankingText(row.ranking) }}
            </span>
            <span v-else class="text-gray">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="得分" width="80" show-overflow-tooltip />
        <el-table-column prop="department" label="院系" min-width="100" show-overflow-tooltip />
        <el-table-column prop="className" label="班级" min-width="100" show-overflow-tooltip />
        <el-table-column prop="judgeName" label="裁判员" min-width="100" show-overflow-tooltip />
        <el-table-column prop="recordTime" label="录入时间" min-width="140">
          <template #default="{ row }">
            {{ formatDateTime(row.recordTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              link 
              type="primary" 
              @click="handleViewDetail(row)"
            >
              查看
            </el-button>
            <el-button 
              link 
              type="primary" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              link 
              type="danger" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 成绩录入/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="scoreFormRef"
        :model="scoreForm"
        :rules="scoreFormRules"
        label-width="120px"
      >
        <el-form-item label="比赛项目" prop="eventId">
          <el-select 
            v-model="scoreForm.eventId" 
            placeholder="请选择比赛项目" 
            filterable 
            style="width: 100%;"
            @change="handleScoreEventChange"
          >
            <el-option 
              v-for="event in events" 
              :key="event.id" 
              :label="`${event.eventName} - ${event.eventCode}`" 
              :value="event.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="运动员" prop="athleteId">
          <el-select 
            v-model="scoreForm.athleteId" 
            placeholder="请选择运动员" 
            filterable 
            style="width: 100%;"
            @change="handleAthleteChange"
          >
            <el-option 
              v-for="registration in eventRegistrations" 
              :key="registration.athleteId" 
              :label="`${registration.athleteName}(${registration.athleteNumber}) - ${registration.athleteClass}`" 
              :value="registration.athleteId"
              :disabled="hasExistingScore(registration.athleteId)"
            >
              <div>
                <span>{{ registration.athleteName }}({{ registration.athleteNumber }})</span>
                <span style="float: right; color: #8492a6; font-size: 13px;">{{ registration.athleteClass }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="成绩值" prop="scoreValue">
          <el-input 
            v-model="scoreForm.scoreValue" 
            placeholder="请输入成绩值" 
          >
            <template #append>{{ getScoreUnit() }}</template>
          </el-input>
          <div class="form-tip">
            {{ getScoreInputTip() }}
          </div>
        </el-form-item>
        
        <el-form-item label="成绩类型" prop="scoreType">
          <el-radio-group v-model="scoreForm.scoreType">
            <el-radio value="time">时间</el-radio>
            <el-radio value="distance">距离</el-radio>
            <el-radio value="score">分数</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="成绩类别" prop="isFinal">
          <el-radio-group v-model="scoreForm.isFinal">
            <el-radio :value="0">预赛</el-radio>
            <el-radio :value="1">决赛</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="裁判员">
          <el-select v-model="scoreForm.judgeId" placeholder="请选择裁判员" filterable style="width: 100%;">
            <el-option 
              v-for="judge in judges" 
              :key="judge.id" 
              :label="`${judge.realName} - ${judge.specialty}`" 
              :value="judge.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input 
            v-model="scoreForm.remarks" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '录入' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="成绩详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="运动员姓名">{{ scoreDetail.athleteName }}</el-descriptions-item>
        <el-descriptions-item label="学号">{{ scoreDetail.studentNumber }}</el-descriptions-item>
        <el-descriptions-item label="院系">{{ scoreDetail.department }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ scoreDetail.className }}</el-descriptions-item>
        <el-descriptions-item label="比赛项目">{{ scoreDetail.eventName }}</el-descriptions-item>
        <el-descriptions-item label="项目编码">{{ scoreDetail.eventCode }}</el-descriptions-item>
        <el-descriptions-item label="原始成绩">{{ scoreDetail.scoreValue }}</el-descriptions-item>
        <el-descriptions-item label="格式化成绩">{{ scoreDetail.formattedScoreValue }}</el-descriptions-item>
        <el-descriptions-item label="成绩类型">{{ getScoreTypeText(scoreDetail.scoreType) }}</el-descriptions-item>
        <el-descriptions-item label="成绩类别">{{ scoreDetail.isFinal === 1 ? '决赛' : '预赛' }}</el-descriptions-item>
        <el-descriptions-item label="排名">{{ getRankingText(scoreDetail.ranking) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="得分">{{ scoreDetail.points || '-' }}</el-descriptions-item>
        <el-descriptions-item label="裁判员">{{ scoreDetail.judgeName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="记录员">{{ scoreDetail.recorderName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="录入时间">{{ formatDateTime(scoreDetail.recordTime) }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ scoreDetail.status === 1 ? '有效' : '无效' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ scoreDetail.remarks || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 批量录入对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量录入成绩" width="900px">
      <div class="batch-entry-header">
        <el-form :model="batchForm" inline>
          <el-form-item label="比赛项目">
            <el-select 
              v-model="batchForm.eventId" 
              placeholder="请选择比赛项目" 
              filterable 
              style="width: 200px;"
              @change="handleBatchEventChange"
            >
              <el-option 
                v-for="event in events" 
                :key="event.id" 
                :label="event.eventName" 
                :value="event.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="成绩类别">
            <el-radio-group v-model="batchForm.isFinal">
              <el-radio :value="0">预赛</el-radio>
              <el-radio :value="1">决赛</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="batchScoreList" stripe style="width: 100%" max-height="400">
        <el-table-column prop="athleteName" label="运动员" width="120" />
        <el-table-column prop="studentNumber" label="学号" width="120" />
        <el-table-column prop="className" label="班级" width="120" />
        <el-table-column label="成绩值" width="150">
          <template #default="{ row, $index }">
            <el-input 
              v-model="row.scoreValue" 
              placeholder="请输入成绩"
              @change="updateBatchScore($index, 'scoreValue', row.scoreValue)"
            />
          </template>
        </el-table-column>
        <el-table-column label="成绩类型" width="120">
          <template #default="{ row, $index }">
            <el-select 
              v-model="row.scoreType" 
              placeholder="类型"
              @change="updateBatchScore($index, 'scoreType', row.scoreType)"
            >
              <el-option label="时间" value="time" />
              <el-option label="距离" value="distance" />
              <el-option label="分数" value="score" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template #default="{ row, $index }">
            <el-input 
              v-model="row.remarks" 
              placeholder="备注"
              @change="updateBatchScore($index, 'remarks', row.remarks)"
            />
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchSubmit" :loading="batchSubmitLoading">
            批量录入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { 
  getScoreList, recordScore, updateScore, deleteScore, 
  getScoreDetail, batchRecordScores, calculateRankings,
  getEventRegistrations
} from '@/api/score'
import { verifyCheckin } from '@/api/checkin'
import { getEventList } from '@/api/event'
import { getJudgeList } from '@/api/judge'
import {
  Plus, Search, Refresh, Delete, Upload, Download
} from '@element-plus/icons-vue'

// 用户状态
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const scoreList = ref([])
const selectedScores = ref([])
const events = ref([])
const judges = ref([])
const eventRegistrations = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  eventId: null,
  isFinal: null
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 成绩统计
const scoreStats = reactive({
  total: 0,
  preliminary: 0,
  final: 0,
  participants: 0
})

// 表单对话框
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentScoreId = ref(null)
const submitLoading = ref(false)
const scoreFormRef = ref(null)

// 详情对话框
const detailDialogVisible = ref(false)
const scoreDetail = ref({})

// 批量录入对话框
const batchDialogVisible = ref(false)
const batchSubmitLoading = ref(false)
const batchScoreList = ref([])

// 成绩表单
const scoreForm = reactive({
  eventId: null,
  athleteId: null,
  registrationId: null,
  scoreValue: '',
  scoreType: 'time',
  isFinal: 0,
  judgeId: null,
  remarks: ''
})

// 批量录入表单
const batchForm = reactive({
  eventId: null,
  isFinal: 0
})

// 表单验证规则
const scoreFormRules = {
  eventId: [
    { required: true, message: '请选择比赛项目', trigger: 'change' }
  ],
  athleteId: [
    { required: true, message: '请选择运动员', trigger: 'change' }
  ],
  scoreValue: [
    { required: true, message: '请输入成绩值', trigger: 'blur' }
  ],
  scoreType: [
    { required: true, message: '请选择成绩类型', trigger: 'change' }
  ],
  isFinal: [
    { required: true, message: '请选择成绩类别', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑成绩' : '录入成绩'
})

const selectedEvent = computed(() => {
  return searchForm.eventId
})

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取成绩类型文本
const getScoreTypeText = (scoreType) => {
  const typeMap = {
    time: '时间',
    distance: '距离',
    score: '分数'
  }
  return typeMap[scoreType] || scoreType
}

// 获取成绩类型标签类型
const getScoreTypeTagType = (scoreType) => {
  const typeMap = {
    time: 'primary',
    distance: 'success',
    score: 'warning'
  }
  return typeMap[scoreType] || ''
}

// 获取排名文本
const getRankingText = (ranking) => {
  if (!ranking || ranking <= 0) return ''
  
  switch (ranking) {
    case 1: return '🥇 第一名'
    case 2: return '🥈 第二名'
    case 3: return '🥉 第三名'
    default: return `第${ranking}名`
  }
}

// 获取成绩单位
const getScoreUnit = () => {
  switch (scoreForm.scoreType) {
    case 'time': return '秒'
    case 'distance': return '米'
    case 'score': return '分'
    default: return ''
  }
}

// 获取输入提示
const getScoreInputTip = () => {
  switch (scoreForm.scoreType) {
    case 'time': return '请输入秒数，如：10.85'
    case 'distance': return '请输入米数，如：8.50'
    case 'score': return '请输入分数，如：95.5'
    default: return ''
  }
}

// 检查是否已有成绩
const hasExistingScore = (athleteId) => {
  return scoreList.value.some(score => 
    score.athleteId === athleteId && 
    score.eventId === scoreForm.eventId &&
    score.isFinal === scoreForm.isFinal
  )
}

// 加载成绩列表
const loadScoreList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    const response = await getScoreList(params)
    scoreList.value = response.data.records || []
    pagination.total = response.data.total || 0
    
    updateScoreStats()
  } catch (error) {
    console.error('加载成绩列表失败:', error)
    ElMessage.error('加载成绩列表失败')
  } finally {
    loading.value = false
  }
}

// 更新成绩统计
const updateScoreStats = () => {
  scoreStats.total = scoreList.value.length
  scoreStats.preliminary = scoreList.value.filter(item => item.isFinal === 0).length
  scoreStats.final = scoreList.value.filter(item => item.isFinal === 1).length
  
  // 计算参赛人数（去重）
  const uniqueAthletes = new Set(scoreList.value.map(item => item.athleteId))
  scoreStats.participants = uniqueAthletes.size
}

// 加载比赛项目列表
const loadEvents = async () => {
  try {
    const response = await getEventList({ current: 1, size: 1000, status: 1 })
    events.value = response.data.records || []
  } catch (error) {
    console.error('加载比赛项目列表失败:', error)
  }
}

// 加载裁判员列表
const loadJudges = async () => {
  try {
    const response = await getJudgeList({ current: 1, size: 1000, status: 1 })
    judges.value = response.data.records || []
  } catch (error) {
    console.error('加载裁判员列表失败:', error)
  }
}

// 加载项目报名列表
const loadEventRegistrations = async (eventId) => {
  try {
    const response = await getEventRegistrations(eventId)
    eventRegistrations.value = response.data || []
  } catch (error) {
    console.error('加载项目报名列表失败:', error)
    eventRegistrations.value = []
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadScoreList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    eventId: null,
    isFinal: null
  })
  handleSearch()
}

// 项目变化处理
const handleEventChange = (eventId) => {
  if (eventId) {
    loadScoreList()
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadScoreList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadScoreList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedScores.value = selection
}

// 新增成绩
const handleAdd = () => {
  isEdit.value = false
  currentScoreId.value = null
  resetScoreForm()
  dialogVisible.value = true
}

// 编辑成绩
const handleEdit = (row) => {
  isEdit.value = true
  currentScoreId.value = row.id
  Object.assign(scoreForm, {
    eventId: row.eventId,
    athleteId: row.athleteId,
    registrationId: row.registrationId,
    scoreValue: row.scoreValue,
    scoreType: row.scoreType,
    isFinal: row.isFinal,
    judgeId: row.judgeId,
    remarks: row.remarks || ''
  })
  
  // 加载对应项目的报名列表
  if (row.eventId) {
    loadEventRegistrations(row.eventId)
  }
  
  dialogVisible.value = true
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const response = await getScoreDetail(row.id)
    scoreDetail.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取成绩详情失败:', error)
    ElMessage.error('获取成绩详情失败')
  }
}

// 删除成绩
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除运动员 ${row.athleteName} 的成绩记录吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteScore(row.id)
    ElMessage.success('删除成功')
    loadScoreList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除成绩失败:', error)
      ElMessage.error('删除成绩失败')
    }
  }
}

// 成绩表单项目变化
const handleScoreEventChange = (eventId) => {
  if (eventId) {
    loadEventRegistrations(eventId)
    scoreForm.athleteId = null
    scoreForm.registrationId = null
  }
}

// 运动员变化
const handleAthleteChange = (athleteId) => {
  if (athleteId) {
    const registration = eventRegistrations.value.find(r => r.athleteId === athleteId)
    if (registration) {
      scoreForm.registrationId = registration.id
    }
  }
}

// 批量录入
const handleBatchEntry = () => {
  batchForm.eventId = null
  batchForm.isFinal = 0
  batchScoreList.value = []
  batchDialogVisible.value = true
}

// 批量录入项目变化
const handleBatchEventChange = async (eventId) => {
  if (eventId) {
    try {
      const response = await getEventRegistrations(eventId)
      batchScoreList.value = response.data.map(registration => ({
        athleteId: registration.athleteId,
        athleteName: registration.athleteName,
        studentNumber: registration.athleteNumber,
        className: registration.athleteClass,
        registrationId: registration.id,
        scoreValue: '',
        scoreType: 'time',
        remarks: ''
      }))
    } catch (error) {
      console.error('加载项目报名失败:', error)
      ElMessage.error('加载项目报名失败')
    }
  }
}

// 更新批量成绩
const updateBatchScore = (index, field, value) => {
  batchScoreList.value[index][field] = value
}

// 批量提交
const handleBatchSubmit = async () => {
  try {
    if (!batchForm.eventId) {
      ElMessage.error('请选择比赛项目')
      return
    }

    const validScores = batchScoreList.value.filter(item => item.scoreValue)
    if (validScores.length === 0) {
      ElMessage.error('请至少录入一个成绩')
      return
    }

    batchSubmitLoading.value = true

    const scores = validScores.map(item => ({
      eventId: batchForm.eventId,
      athleteId: item.athleteId,
      registrationId: item.registrationId,
      scoreValue: item.scoreValue,
      scoreType: item.scoreType,
      isFinal: batchForm.isFinal,
      remarks: item.remarks
    }))

    await batchRecordScores(scores)
    ElMessage.success(`成功录入 ${scores.length} 条成绩`)
    batchDialogVisible.value = false
    loadScoreList()
  } catch (error) {
    console.error('批量录入失败:', error)
    ElMessage.error('批量录入失败')
  } finally {
    batchSubmitLoading.value = false
  }
}

// 重新计算排名
const handleCalculateRankings = async () => {
  try {
    if (!selectedEvent.value) {
      ElMessage.error('请先选择比赛项目')
      return
    }

    await ElMessageBox.confirm(
      '确定要重新计算该项目的排名吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await calculateRankings(selectedEvent.value, {
      isFinal: searchForm.isFinal
    })
    ElMessage.success('排名计算完成')
    loadScoreList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('计算排名失败:', error)
      ElMessage.error('计算排名失败')
    }
  }
}

// 导出成绩
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 提交表单
const handleSubmit = async () => {
  if (!scoreFormRef.value) return
  
  try {
    await scoreFormRef.value.validate()
    submitLoading.value = true
    
    // 如果是新增成绩，需要验证运动员是否已检录
    if (!isEdit.value) {
      try {
        const checkinResponse = await verifyCheckin(scoreForm.athleteId, scoreForm.eventId)
        if (!checkinResponse.data) {
          ElMessage.error('该运动员尚未检录，无法录入成绩！请先完成检录。')
          return
        }
      } catch (error) {
        ElMessage.error('检录验证失败，请检查运动员检录状态')
        return
      }
    }
    
    if (isEdit.value) {
      await updateScore(currentScoreId.value, scoreForm)
      ElMessage.success('更新成功')
    } else {
      await recordScore(scoreForm)
      ElMessage.success('录入成功')
    }
    
    dialogVisible.value = false
    loadScoreList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 对话框关闭处理
const handleDialogClose = (done) => {
  resetScoreForm()
  if (typeof done === 'function') {
    done()
  }
}

// 重置表单
const resetScoreForm = () => {
  if (scoreFormRef.value) {
    scoreFormRef.value.resetFields()
    scoreFormRef.value.clearValidate()
  }
  
  Object.assign(scoreForm, {
    eventId: null,
    athleteId: null,
    registrationId: null,
    scoreValue: '',
    scoreType: 'time',
    isFinal: 0,
    judgeId: null,
    remarks: ''
  })
  
  eventRegistrations.value = []
}

// 组件挂载时加载数据
onMounted(() => {
  loadScoreList()
  loadEvents()
  loadJudges()
})
</script>

<style scoped>
.score-entry {
  padding: 20px;
  width: 100%;
  max-width: 100%;
  overflow-x: auto;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.left-actions,
.right-actions {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-value.total {
  color: #409eff;
}

.stat-value.preliminary {
  color: #e6a23c;
}

.stat-value.final {
  color: #67c23a;
}

.stat-value.participants {
  color: #f56c6c;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.table-card {
  margin-bottom: 20px;
  width: 100%;
}

.table-card :deep(.el-table) {
  width: 100% !important;
}

.table-card :deep(.el-table__body-wrapper) {
  width: 100% !important;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.text-gray {
  color: #909399;
}

.batch-entry-header {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
